package fr.uniscol;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import fr.uniscol.model.IUniscolUser;
import fr.uniscol.model.valid.LoginFormModel;
import fr.uniscol.mvc.UniscolActionsUrl;
import fr.uniscol.service.IAnneeScolaireService;
import fr.uniscol.service.ILoginService;
import org.springframework.context.ApplicationContext;

@Controller
public class LoginController extends UniscolMainController {

	private static final Logger log = Logger.getLogger(LoginController.class);
	
	@Autowired
	private ILoginService loginService;
	
	@Autowired
	private IAnneeScolaireService anneeScolaireService;
    
    @Autowired
    private ApplicationContext applicationContext;
	
	@ModelAttribute("loginFormModel")
	public LoginFormModel getLoginFormModel(){
		return new LoginFormModel();
	}
	
	@RequestMapping(value=UniscolActionsUrl.AUTHENTIFIER, method=RequestMethod.GET)
	public ModelAndView login(Model model){
		
		//model.addAttribute("loginFormModel", getLoginFormModel());
		//getLoginFormModel();
		
		return new ModelAndView("login", "loginFormModel", new LoginFormModel());
	}
	
	@RequestMapping(value=UniscolActionsUrl.AUTHENTIFIER, method=RequestMethod.POST)
	public String login(@ModelAttribute LoginFormModel loginFormModel, BindingResult results, Model model, HttpSession session){
		
		log.info("Authentification demandée : " + loginFormModel.getLogin() + " / " + loginFormModel.getPassword());
		
		loginFormModel.validate(loginFormModel, results);
		
		String nextView = "login";
		IUniscolUser utilisateur = loginService.authentifierUser(loginFormModel.getLogin(), loginFormModel.getPassword());
		if(utilisateur == null){
			results.rejectValue("login", "login.error", "Login ou mot de passe incorrect !");
		
		}else{
			openSession(utilisateur, session);
		}
		
		if(!results.hasErrors()){
            if(utilisateur.isSuperAdmin()){
                return "redirect:admin/bases";
            }
			return "redirect:home";
		}
		
		return nextView;
	}
	
	@RequestMapping("/disconnect")
	public String disconnect(HttpSession session){
		
		session.invalidate();
		
		return "redirect:login";
	}
	
	private void openSession(IUniscolUser user, HttpSession session){
		
		log.info("Création d'une nouvelle session pour " + user.getLogin());
		
		session.setMaxInactiveInterval(1600);
		
        user.setIdentite(user.getIdentite());
        user.setAuthentifie(true);
        
        if(!user.isSuperAdmin()){
            // Etablissement
            user.setBaseSelectionnee(anneeScolaireService.getBaseById(user.getBaseSelectionnee().getId()));
        }
        
        session.setAttribute("utilisateur", user);
	}
	
	@RequestMapping("/session.expiree")
	public ModelAndView sessionExpiree(Model model, HttpSession session){
		
		session.invalidate();
		
		alertInfo("session.expiree", "Votre session a expirée, veuillez vous reconnecter.", model);
		
		return login(model);
	}
}
